package load;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import entity.MapInfoSet;
import entity.Point;
import entity.VehicleRealtimeInfo;
import entity.enums.HikDeviceStatus;
import global.Global;
import global.InitCache;

import java.io.*;
import java.util.List;

/**
 * 初始化加载信息
 *
 * @author zhouwz
 * @date 2020/11/3 14:05
 */
public class InitLoad {

    /**
     * 车辆信息加载
     */
    public static void vehicleStatusLoad() {
        try {
            Point currentPoint = InitCache.crossPointCache.get(InitCache.randomPoint.get(RandomUtil.randomInt(0, InitCache.randomPoint.size() - 1)));
            // 随机点位(可能存在与其他车辆上报的点位一样)

            InitCache.realtimeStatus =
                    new VehicleRealtimeInfo(
                            (int) (currentPoint.getXCoordinate() * 1000),
                            (int) (currentPoint.getYCoordinate() * 1000),
                            RandomUtil.randomInt(-180, 180),
                            currentPoint,
                            RandomUtil.randomInt(60, 100),
                            HikDeviceStatus.STATUS_1);
        } catch (Exception e) {
            vehicleStatusLoad();
        }
    }


    /**
     * 地图数据加载
     */
    public static void mapInfoLoad() {
        File file = new File(InitCache.pathAndFilename);
        FileReader fileReader = null;
        Reader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            fileReader = new FileReader(file);
            reader = new InputStreamReader(new FileInputStream(file), Global.CHARSET_NAME);
            int ch;
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                assert fileReader != null;
                fileReader.close();
                assert reader != null;
                reader.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        List<Point> records = JSONUtil.toBean(sb.toString(), MapInfoSet.class).getRECORDS();
        for (int i = 0; i < records.size(); i++) {
            Point point = records.get(i);
            if (Global.ELEMENT_TYPE_POINT.equals(point.getElementType())) {
                String cacheKey = StrUtil.format("{}_{}", (int) (point.getXCoordinate() * 1000), (int) (point.getYCoordinate() * 1000));
                InitCache.crossPointCache.put(cacheKey, point);
                InitCache.randomPoint.put(i, cacheKey);
            }
        }
    }
}
